package service

import (
	"encoding/base64"
	commonConfig "gin-worked/app/common/config"
	"gin-worked/app/common/model"
	"gin-worked/config"
)

type LoginApi struct {
	Token string
}

func Login(username string, password string) Res {

	i := 0
	data := &model.User{
		Username:   username,
		DeleteTime: &i,
	}

	filed := []string{"id", "username", "password", "salt", "type", "delete_time", "status"}

	userInfo, err := model.GetUserInfo(data, filed)

	if err != nil {
		return Res{0, err.Error(), ""}
	}

	if userInfo.Status != 1 {
		return Res{0, "账号异常请联系管理员", ""}
	}

	key := []byte(userInfo.Salt)
	key = config.PadToBlockSize(key)

	encrypt, _ := config.Encrypt([]byte(password), key)

	if base64.StdEncoding.EncodeToString(encrypt) != userInfo.Password {
		return Res{0, "密码不正确", encrypt}
	}

	token, tokenErr := commonConfig.CreateToken(userInfo.UserInfo.UserId, userInfo.UserInfo.Nickname, userInfo.UserInfo.Tel, userInfo.UserInfo.HeadImg, userInfo.UserInfo.Name)

	if tokenErr != nil {
		return Res{0, tokenErr.Error(), ""}
	}

	content := LoginApi{
		Token: token,
	}
	expireTime := commonConfig.GetTokenExpireTime()

	errors := config.Rdb.Set(config.Rctx, token, token, expireTime).Err() //c_ 用于区分后台管理系统的缓存 缓存用户token

	if errors != nil {
		return Res{Code: 0, Msg: errors, Data: ""}
	}

	return Res{Code: 1, Msg: "success", Data: content}
}
